<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
      :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px)">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" inline label-position="left" label-width="100px">
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="交易卡号" prop="cardNumber">
                  <el-input v-model="queryParams.cardNumber" placeholder="请输入交易卡号" clearable
                    @keyup.enter="handleQuery" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="交易账号" prop="accountNumber">
                  <el-input v-model="queryParams.accountNumber" placeholder="请输入交易账号" clearable
                    @keyup.enter="handleQuery" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="交易时间" prop="transactionTime">
                  <el-date-picker v-model="dateRangeTransactionTime" value-format="YYYY-MM-DD HH:mm:ss" type="daterange"
                    range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="收付标志" prop="paymentFlag">
                  <el-select v-model="queryParams.paymentFlag" placeholder="请选择收付标志" clearable>
                    <el-option v-for="dict in stkj_payment_flag" :key="dict.value" :label="dict.label"
                      :value="dict.value" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="对手账号" prop="counterpartyCardNumber">
                  <el-input v-model="queryParams.counterpartyCardNumber" placeholder="请输入交易对手账卡号" clearable
                    @keyup.enter="handleQuery" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="排序字段" prop="sortField">
                  <el-select v-model="queryParams.sortField" placeholder="请选择排序字段" clearable>
                    <el-option v-for="dict in sktj_sort_field" :key="dict.value" :label="dict.label"
                      :value="dict.value" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="排序方式" prop="ascOrDesc">
                  <el-select v-model="queryParams.ascOrDesc" placeholder="请选择排序方式" clearable>
                    <el-option v-for="dict in sktj_asc_desc" :key="dict.value" :label="dict.label"
                      :value="dict.value" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="24" :offset="20">
                <el-form-item label-width="0">
                  <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                  <el-button icon="Refresh" @click="resetQuery">重置</el-button>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </el-card>
      </div>
    </transition>


    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd"
              v-hasPermi="['liushui:liushui:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()"
              v-hasPermi="['liushui:liushui:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-dropdown class="mt-[1px]">
              <el-button plain type="danger">
                删除
                <el-icon class="el-icon--right"><arrow-down /></el-icon></el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item icon="Delete" :disabled="multiple" @click="handleDelete()">删除</el-dropdown-item>
                  <el-dropdown-item icon="Delete" @click="handleDeleteAll()"> 全部删除</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </el-col>
          <el-col :span="1.5">
            <el-dropdown class="mt-[1px]">
              <el-button plain type="info">
                导出
                <el-icon class="el-icon--right"><arrow-down /></el-icon></el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item icon="Download" @click="handleExport">全部导出</el-dropdown-item>
                  <el-dropdown-item icon="Download" :disabled="multiple" @click="handleExportByIds()">
                    选择导出</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="liushuiList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="自增id" align="center" prop="id" v-if="false" />
        <el-table-column v-if="hasData('cardNumber')" label="交易卡号" align="center" prop="cardNumber" width="180"
          :show-overflow-tooltip="true" />
        <el-table-column v-if="hasData('accountNumber')" label="交易账号" align="center" prop="accountNumber" width="180"
          :show-overflow-tooltip="true" />
        <el-table-column v-if="hasData('queryResultReason')" label="查询结果" align="center" prop="queryResultReason"
          width="100" :show-overflow-tooltip="true" />
        <el-table-column v-if="hasData('accountName')" label="交易户名" align="center" prop="accountName" width="180"
          :show-overflow-tooltip="true" />
        <el-table-column v-if="hasData('idNumber')" label="交易证件号码" align="center" prop="idNumber" width="180"
          :show-overflow-tooltip="true" />
        <el-table-column v-if="hasData('transactionTime')" label="交易时间" align="center" prop="transactionTime"
          width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.transactionTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column v-if="hasData('transactionAmount')" label="交易金额" align="center" prop="transactionAmount" />
        <el-table-column v-if="hasData('balance')" label="交易余额" align="center" prop="balance" />
        <el-table-column v-if="hasData('paymentFlag')" label="收付标志" align="center" prop="paymentFlag">
          <template #default="scope">
            <dict-tag :options="stkj_payment_flag" :value="scope.row.paymentFlag" />
          </template>
        </el-table-column>
        <el-table-column v-if="hasData('counterpartyCardNumber')" label="交易对手账卡号" align="center"
          prop="counterpartyCardNumber" width="180" :show-overflow-tooltip="true" />
        <el-table-column v-if="hasData('cashFlag')" label="现金标志" align="center" prop="cashFlag" />
        <el-table-column v-if="hasData('counterpartyName')" label="对手户名" align="center" prop="counterpartyName"
          :show-overflow-tooltip="true" />
        <el-table-column v-if="hasData('counterpartyIdNumber')" label="对手身份证号" align="center"
          prop="counterpartyIdNumber" width="180" :show-overflow-tooltip="true" />
        <el-table-column v-if="hasData('counterpartyBank')" label="对手开户银行" align="center" prop="counterpartyBank"
          width="120" :show-overflow-tooltip="true" />
        <el-table-column v-if="hasData('summary')" label="摘要说明" align="center" prop="summary" width="100"
          :show-overflow-tooltip="true" />
        <el-table-column v-if="hasData('currency')" label="交易币种" align="center" prop="currency" width="100"
          :show-overflow-tooltip="true" />
        <el-table-column v-if="hasData('branchName')" label="交易网点名称" align="center" prop="branchName" width="120"
          :show-overflow-tooltip="true" />
        <el-table-column v-if="hasData('transactionLocation')" label="交易发生地" align="center" prop="transactionLocation"
          width="120" :show-overflow-tooltip="true" />
        <el-table-column v-if="hasData('transactionSuccess')" label="交易是否成功" align="center" prop="transactionSuccess"
          width="120" />
        <el-table-column v-if="hasData('voucherNumber')" label="传票号" align="center" prop="voucherNumber" width="100"
          :show-overflow-tooltip="true" />
        <el-table-column v-if="hasData('ipAddress')" label="IP地址" align="center" prop="ipAddress" width="140"
          :show-overflow-tooltip="true" />
        <el-table-column v-if="hasData('macAddress')" label="MAC地址" align="center" prop="macAddress" width="160"
          :show-overflow-tooltip="true" />
        <el-table-column v-if="hasData('counterpartyBalance')" label="对手交易余额" align="center" prop="counterpartyBalance"
          width="100" :show-overflow-tooltip="true" />
        <el-table-column v-if="hasData('transactionId')" label="交易流水号" align="center" prop="transactionId" width="180"
          :show-overflow-tooltip="true" />
        <el-table-column v-if="hasData('logId')" label="日志号" align="center" prop="logId" width="100"
          :show-overflow-tooltip="true" />
        <el-table-column v-if="hasData('voucherType')" label="凭证种类" align="center" prop="voucherType" />
        <el-table-column v-if="hasData('voucherCode')" label="凭证号" align="center" prop="voucherCode" width="100"
          :show-overflow-tooltip="true" />
        <el-table-column v-if="hasData('tellerId')" label="交易柜员号" align="center" prop="tellerId" width="100"
          :show-overflow-tooltip="true" />
        <el-table-column v-if="hasData('remark')" label="备注" align="center" prop="remark" width="100"
          :show-overflow-tooltip="true" />
        <el-table-column v-if="hasData('merchantName')" label="商户名称" align="center" prop="merchantName" width="100"
          :show-overflow-tooltip="true" />
        <el-table-column v-if="hasData('merchantCode')" label="商户代码" align="center" prop="merchantCode" width="160"
          :show-overflow-tooltip="true" />
        <el-table-column v-if="hasData('transactionType')" label="交易类型" align="center" prop="transactionType" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                v-hasPermi="['liushui:liushui:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                v-hasPermi="['liushui:liushui:remove']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改银行流水对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="600px" append-to-body>
      <el-form ref="liushuiFormRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="交易卡号" prop="cardNumber">
          <el-input v-model="form.cardNumber" placeholder="请输入交易卡号" />
        </el-form-item>
        <el-form-item label="交易账号" prop="accountNumber">
          <el-input v-model="form.accountNumber" placeholder="请输入交易账号" />
        </el-form-item>
        <el-form-item label="查询结果" prop="queryResultReason">
          <el-input v-model="form.queryResultReason" placeholder="请输入查询反馈结果原因" />
        </el-form-item>
        <el-form-item label="交易户名" prop="accountName">
          <el-input v-model="form.accountName" placeholder="请输入交易户名" />
        </el-form-item>
        <el-form-item label="交易证件号码" prop="idNumber">
          <el-input v-model="form.idNumber" placeholder="请输入交易证件号码" />
        </el-form-item>
        <el-form-item label="交易时间" prop="transactionTime">
          <el-date-picker clearable v-model="form.transactionTime" type="datetime" value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择交易时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="交易金额" prop="transactionAmount">
          <el-input v-model="form.transactionAmount" placeholder="请输入交易金额" />
        </el-form-item>
        <el-form-item label="交易余额" prop="balance">
          <el-input v-model="form.balance" placeholder="请输入交易余额" />
        </el-form-item>
        <el-form-item label="收付标志" prop="paymentFlag">
          <el-select v-model="form.paymentFlag" placeholder="请选择收付标志">
            <el-option v-for="dict in stkj_payment_flag" :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="交易对手账卡号" prop="counterpartyCardNumber">
          <el-input v-model="form.counterpartyCardNumber" placeholder="请输入交易对手账卡号" />
        </el-form-item>
        <el-form-item label="现金标志" prop="cashFlag">
          <el-input v-model="form.cashFlag" placeholder="请输入现金标志" />
        </el-form-item>
        <el-form-item label="对手户名" prop="counterpartyName">
          <el-input v-model="form.counterpartyName" placeholder="请输入对手户名" />
        </el-form-item>
        <el-form-item label="对手身份证号" prop="counterpartyIdNumber">
          <el-input v-model="form.counterpartyIdNumber" placeholder="请输入对手身份证号" />
        </el-form-item>
        <el-form-item label="对手开户银行" prop="counterpartyBank">
          <el-input v-model="form.counterpartyBank" placeholder="请输入对手开户银行" />
        </el-form-item>
        <el-form-item label="摘要说明" prop="summary">
          <el-input v-model="form.summary" placeholder="请输入摘要说明" />
        </el-form-item>
        <el-form-item label="交易币种" prop="currency">
          <el-input v-model="form.currency" placeholder="请输入交易币种" />
        </el-form-item>
        <el-form-item label="交易网点名称" prop="branchName">
          <el-input v-model="form.branchName" placeholder="请输入交易网点名称" />
        </el-form-item>
        <el-form-item label="交易发生地" prop="transactionLocation">
          <el-input v-model="form.transactionLocation" placeholder="请输入交易发生地" />
        </el-form-item>
        <el-form-item label="交易是否成功" prop="transactionSuccess">
          <el-input v-model="form.transactionSuccess" placeholder="请输入交易是否成功" />
        </el-form-item>
        <el-form-item label="传票号" prop="voucherNumber">
          <el-input v-model="form.voucherNumber" placeholder="请输入传票号" />
        </el-form-item>
        <el-form-item label="IP地址" prop="ipAddress">
          <el-input v-model="form.ipAddress" placeholder="请输入IP地址" />
        </el-form-item>
        <el-form-item label="MAC地址" prop="macAddress">
          <el-input v-model="form.macAddress" placeholder="请输入MAC地址" />
        </el-form-item>
        <el-form-item label="对手交易余额" prop="counterpartyBalance">
          <el-input v-model="form.counterpartyBalance" placeholder="请输入对手交易余额" />
        </el-form-item>
        <el-form-item label="交易流水号" prop="transactionId">
          <el-input v-model="form.transactionId" placeholder="请输入交易流水号" />
        </el-form-item>
        <el-form-item label="日志号" prop="logId">
          <el-input v-model="form.logId" placeholder="请输入日志号" />
        </el-form-item>
        <el-form-item label="凭证种类" prop="voucherType">
          <el-input v-model="form.voucherType" placeholder="请输入凭证种类" />
        </el-form-item>
        <el-form-item label="凭证号" prop="voucherCode">
          <el-input v-model="form.voucherCode" placeholder="请输入凭证号" />
        </el-form-item>
        <el-form-item label="交易柜员号" prop="tellerId">
          <el-input v-model="form.tellerId" placeholder="请输入交易柜员号" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
        <el-form-item label="商户名称" prop="merchantName">
          <el-input v-model="form.merchantName" placeholder="请输入商户名称" />
        </el-form-item>
        <el-form-item label="商户代码" prop="merchantCode">
          <el-input v-model="form.merchantCode" placeholder="请输入商户代码" />
        </el-form-item>
        <el-form-item label="交易类型" prop="transactionType">
          <el-input v-model="form.transactionType" placeholder="请输入交易类型" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Liushui" lang="ts">
import { listLiushui, getLiushui, delLiushui, addLiushui, updateLiushui, exportSelectedLiushui,clearLiushui } from '@/api/liushui/liushui';
import { LiushuiVO, LiushuiQuery, LiushuiForm } from '@/api/liushui/liushui/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { stkj_payment_flag } = toRefs<any>(proxy?.useDict('stkj_payment_flag'));
const { sktj_sort_field } = toRefs<any>(proxy?.useDict('sktj_sort_field'));
const { sktj_asc_desc } = toRefs<any>(proxy?.useDict('sktj_asc_desc'));

const liushuiList = ref<LiushuiVO[]>([]);

const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const dateRangeTransactionTime = ref<[DateModelType, DateModelType]>(['', '']);

const queryFormRef = ref<ElFormInstance>();
const liushuiFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: LiushuiForm = {
  id: undefined,
  cardNumber: undefined,
  accountNumber: undefined,
  queryResultReason: undefined,
  accountName: undefined,
  idNumber: undefined,
  transactionTime: undefined,
  transactionAmount: undefined,
  balance: undefined,
  paymentFlag: undefined,
  counterpartyCardNumber: undefined,
  cashFlag: undefined,
  counterpartyName: undefined,
  counterpartyIdNumber: undefined,
  counterpartyBank: undefined,
  summary: undefined,
  currency: undefined,
  branchName: undefined,
  transactionLocation: undefined,
  transactionSuccess: undefined,
  voucherNumber: undefined,
  ipAddress: undefined,
  macAddress: undefined,
  counterpartyBalance: undefined,
  transactionId: undefined,
  logId: undefined,
  voucherType: undefined,
  voucherCode: undefined,
  tellerId: undefined,
  remark: undefined,
  merchantName: undefined,
  merchantCode: undefined,
  transactionType: undefined,
}
const data = reactive<PageData<LiushuiForm, LiushuiQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    cardNumber: undefined,
    accountNumber: undefined,
    paymentFlag: undefined,
    counterpartyCardNumber: undefined,
    sortField: undefined,
    ascOrDesc: undefined,
    params: {
      transactionTime: undefined,
    }
  },
  rules: {
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询银行流水列表 */
const getList = async () => {
  loading.value = true;
  queryParams.value.params = {};
  proxy?.addDateRange(queryParams.value, dateRangeTransactionTime.value, 'TransactionTime');
  const res = await listLiushui(queryParams.value);
  liushuiList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  liushuiFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  dateRangeTransactionTime.value = ['', ''];
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: LiushuiVO[]) => {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = "添加银行流水";
}

/** 修改按钮操作 */
const handleUpdate = async (row?: LiushuiVO) => {
  reset();
  const _id = row?.id || ids.value[0]
  const res = await getLiushui(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = "修改银行流水";
}

/** 提交按钮 */
const submitForm = () => {
  liushuiFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateLiushui(form.value).finally(() => buttonLoading.value = false);
      } else {
        await addLiushui(form.value).finally(() => buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("操作成功");
      dialog.visible = false;
      await getList();
    }
  });
}

/** 删除按钮操作 */
const handleDelete = async (row?: LiushuiVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除银行流水编号为"' + _ids + '"的数据项？').finally(() => loading.value = false);
  await delLiushui(_ids);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('liushui/liushui/export', {
    ...queryParams.value
  }, `liushui_${new Date().getTime()}.xlsx`)
}


/** 导出选中按钮操作 */
const handleExportByIds = async (row?: LiushuiVO) => {
  try {
    const _ids = Array.isArray(row?.id) ? row?.id : Array.isArray(ids.value) ? ids.value : [];
    // 确保有数据被选中
    if (_ids.length === 0) {
      ElMessage.warning('请至少选择一项进行导出');
      return;
    }

    // 调用后端API进行导出操作，直接处理返回的Blob对象
    const response = await exportSelectedLiushui(_ids);

    // 由于后端直接返回了Blob，我们可以直接处理这个Blob来下载文件
    //const url = window.URL.createObjectURL(new Blob([response]));
    const url = window.URL.createObjectURL(response as unknown as Blob);
    const link = document.createElement('a');
    link.href = url;
    link.setAttribute('download', `liushui_${new Date().getTime()}.xlsx`); // 自定义文件名
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);

    ElMessage.success('导出成功');
  } catch (error) {
    console.error('导出选中数据时发生错误:', error);
    ElMessage.error('导出过程中发生错误，请检查网络或联系管理员');
  }
};


/**检查列中是否有数据，如果没有则隐藏该列 */
const checkColumn = (row: LiushuiVO, column: any) => {
  return row[column.property] ? true : false;
}
const hasData = (prop: string) => {
  // 检查liushuiList中的至少一条数据是否包含prop属性且该属性有值
  return liushuiList.value.some(item => item[prop] && item[prop] !== '');
};


/**清空表数据 */
const handleDeleteAll = async () => {
  try {
      // 确认操作
      await proxy?.$modal.confirm('确定要清空表数据吗');
      // 开始清理并加载列表
      loading.value = true;
      await clearLiushui();
      proxy?.$modal.msgSuccess("清空数据成功");
      getList();
    } catch (error) {
      // 捕获到错误时，关闭加载状态并给出错误提示
      loading.value = false;
      console.error("操作失败", error);
      //ElMessage.error("操作失败，请稍后重试");
    } finally {
      // 确保loading状态被正确关闭
      loading.value = false;
    }
}
onMounted(() => {
  getList();
});

</script>
